package com.halotis.taskLauncher;

import static com.halotis.taskLauncher.Constants.*;

import java.util.HashMap;
import java.util.Map;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;


public class LoaderProperties extends HashMap<String, Map<String, String>> {
	private static final long serialVersionUID = 1L;
	
	// Singleton instance
	private static LoaderProperties properties = null;
	
	private LoaderProperties() throws Exception {
		Document xml = XmlHelper.getXmlDocument(CONFIG_XML_PATH);
		loadSettings(xml);
	}
	
	private void loadSettings(Document xml) {
		Element element = (Element)xml.getElementsByTagName("users").item(0);
		NodeList settings = element.getElementsByTagName("host");
		
		for (int i = 0; i < settings.getLength(); i++) {
			NamedNodeMap attributes = settings.item(i).getAttributes();
			String host = attributes.getNamedItem("name").getNodeValue().toUpperCase();
			String user = attributes.getNamedItem("user").getNodeValue();
			String pass = attributes.getNamedItem("password").getNodeValue();
			Map<String, String> userpass = new HashMap<String, String>();
			userpass.put("user", user);
			userpass.put("password", pass);
			this.put(host, userpass);
		}
	}

	public static LoaderProperties setup() throws Exception {
		if (properties == null) properties = new LoaderProperties(); 			
		return properties;
	}
	
	public static LoaderProperties getInstance() {
		if (properties == null) {
			throw new AssertionError("LoaderProperties should already have static instance set.");
		}
		return properties;
	}
}
